<?php

namespace app\common\traits;

use edward\redis\Redis;
use think\helper\Str;

trait FullThumbPart
{
    public function getFullThumbAttr()
    {
        $value = $this["thumb"] ?? "";
        if ($value) {
            $value = cdnurl($value, true);
        }
        return $value;
    }

    public function getFullImageAttr()
    {
        $value = $this["image"] ?? "";
        if ($value) {
            $value = cdnurl($value, true);
        }
        return $value;
    }


    public function getFullMiniQrCodeAttr()
    {
        $value = $this["mini_qr_code"] ?? "";
        if ($value) {
            $value = cdnurl($value, true);
        }
        return $value;
    }

    public function getFullAvatarAttr()
    {
        $value = $this["avatar"] ?? null;
        if ($value) {
            $value = cdnurl($value, true);
        }
        return $value;
    }


    public function getFullBackgroundAttr()
    {
        $value = $this['background'] ?? null;
        if ($value) {
            $value = cdnurl($value, true);
        }
        return $value;
    }

    public function getFullImagesAttr()
    {
        $value = $this['images'] ?? null;
        if ($value) {
            $value = explode(',', $value);
            foreach ($value as &$item) {
                $item = cdnurl($item, true);
            }
        }
        return $value;
    }

    protected function getFullUrl($attribute, bool $isTemporaryUrl = false)
    {
        $value = $this[$attribute] ?? "";
        if ($value) {
            $value = cdnurl($value, true, $isTemporaryUrl);
        }
        return $value;
    }

    protected function getFullUrlByArr($attribute)
    {
        $value = array_filter(explode(',', $this[$attribute] ?? ""));
        if ($value) {
            foreach ($value as &$item) {
                $item = cdnurl($item, true);
            }
        }
        return $value;
    }

    protected function getSourceUrlTemporaryUrl($attribute)
    {
        $playUrl = '';
        if ($value = ($this[$attribute] ?? '')) {
            $md5 = md5(uniqid() . Str::random(10) . time());
            Redis::set($md5, $value, 60 * 60);
            return sprintf(
                "%s://%s:%s/index/index/getSourceRealUrl?sign=%s",
                request()->server('REQUEST_SCHEME'),
                request()->server('SERVER_NAME'),
                request()->server('SERVER_PORT'),
                $md5,
            );
        }
        return $playUrl;
    }

    protected function getSourceUrlTemporaryUrlByValue($value)
    {
        $playUrl = '';
        if ($value) {
            $md5 = md5(uniqid() . Str::random(10) . time());
            Redis::set($md5, $value, 60 * 60);
            return sprintf(
                "%s://%s/index/index/getSourceRealUrl?sign=%s",
                request()->server('REQUEST_SCHEME'),
                request()->server('SERVER_NAME'),
                $md5,
            );
        }
        return $playUrl;
    }
}